﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;
using System.Security.Principal;

namespace MS.InformationManagement.DocumentIDServiceApp
{
    [Guid("7C78B3EE-A723-444F-9444-62B9CE3877F4")]
    internal sealed class DocumentIDServiceDatabase:SPDatabase
    {
        #region Constructors

        public DocumentIDServiceDatabase()
            : base()
        { }

        internal DocumentIDServiceDatabase(SPDatabaseParameters parameters)
            : base (parameters)
        {
            this.Status = SPObjectStatus.Disabled;
        }

        #endregion

        #region SPDatabase

        public override void Provision()
        {
            if (this.Status == SPObjectStatus.Online)
                return;

            this.Status = SPObjectStatus.Provisioning;
            this.Update();

            Dictionary<String, Boolean> options = new Dictionary<string, bool>(1);
            options.Add(SqlDatabaseOption[(int)DatabaseOptions.AutoClose], false);

            SPDatabase.Provision(
                this.DatabaseConnectionString,
                SPUtility.GetGenericSetupPath(@"Template\SQL\DocumentIDServiceApplication.sql"),
                options);

            this.Status = SPObjectStatus.Online;
            this.Update();
        }

        public override void Unprovision()
        {
            base.Unprovision();
        }

        #endregion

        #region Internal methods

        internal void GrantApplicationPoolAccess(SecurityIdentifier processSecurityIdentifier)
        {
            this.GrantAccess(processSecurityIdentifier, "db_owner");
        }

        #endregion
    }
}
